<template>
  <div ref="container" class="monaco-editor" :style="'height: ' + height + 'px'"></div>
</template>

<script>
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api'
export default {
  name: 'AcMonaco',
  props: {
    language: {
      type: String,
      default: 'json'
    },
    oldValue: String,
    value: String,
    height: {
      type: Number,
      default: 500
    }
  },
  data() {
    return {
      previous: '',
      monacoDiffInstance: '',
      // 主要配置
      defaultOpts: {
        value: '',
        theme: 'vs', // 编辑器主题：vs, hc-black, or vs-dark，更多选择详见官网
        roundedSelection: false, // 右侧不显示编辑器预览框
        autoIndent: true, // 自动缩进
        readOnly: false, // 是否只读
        contextmenu: true,
        folding: true
      },
      originalModel: '',
      modifiedModel: ''
    }
  },
  mounted() {
    this.init()
  },
  // 监听父组件传值的变化，实时更新到编辑器中
  watch: {
    oldValue: {
      handler: function(val, oldVal) {
        this.originalModel = monaco.editor.createModel(val, this.language)
        this.monacoDiffInstance.setModel({
          original: this.originalModel,
          modified: this.modifiedModel
        })
      }
    },
    value: {
      handler: function(val, oldVal) {
        this.modifiedModel = monaco.editor.createModel(val, this.language)
        this.monacoDiffInstance.setModel({
          original: this.originalModel,
          modified: this.modifiedModel
        })
        this.$emit('change', this.modifiedModel.getValue())
      }
    }
  },
  methods: {
    init() {
      // 初始化编辑器实例
      this.monacoDiffInstance =
        monaco.editor.createDiffEditor(this.$refs['container'], this.defaultOpts)
      this.originalModel = monaco.editor.createModel(this.oldValue, this.language)
      this.modifiedModel = monaco.editor.createModel(this.value, this.language)
      this.monacoDiffInstance.setModel({
        modified: this.modifiedModel,
        original: this.originalModel
      })
      this.previous = this.value
    },
    // 此方法获取到编辑的最新值，传给父组件
    getValue() {
      const value = this.modifiedModel.getValue()
      this.$emit('change', value)
      // this.$emit('change', this.modifiedModel.getValue())
      // console.log('getvalue是什么', this.modifiedModel.getValue())
    },
    assignment() {
      this.modifiedModel = this.previous
    }
  }
}
</script>

<style lang="less">
.el-dialog__body{
}
.the-code-diff-editor-container {
  width: 100%;
  height: 100%;
  overflow: auto;
  .monaco-editor .scroll-decoration {
    box-shadow: none;
  }
}
</style>
